package com.example.theenvironment;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothGatt;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;

import java.util.List;
//环境
public class Theenvironment {
    public static String SERVICE_UUID = "9AC71523-E48C-4ED1-A9FD-35EADC77231A";
    public static String UUID_FFOA = "9AC71526-E48C-4ED1-A9FD-35EADC77231A";
    //    连接态值
    private static OnConnectionstatus receivedCallback;
    private boolean Connectionstatus=false;
    private boolean ongoing=false;
    private BleDevice bleDevice;
    //    蓝牙收取数据
    private static OnReceivedata monReceivedata;
    //    扫描
    private static Onscanning scanning;
    private static Theenvironment temperature;

    //    提供一个全局的静态方法
    public static Theenvironment sharedCenter() {
        if (temperature == null) {
            synchronized (Theenvironment.class) {
                if (temperature == null) {
                    temperature = new Theenvironment();
                }
            }
        }
        return temperature;
    }


    //初始化蓝牙1
    public static void Initializethe(Activity activity) {


        BluetoothAdapter bluetoothAdapter;
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            bluetoothAdapter.enable();
        }
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
//        Log.i(TAG, "sdk < 28 Q");
            if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                String[] strings =
                        {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
                ActivityCompat.requestPermissions(activity, strings, 1);
            }
        } else {
            if (ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(activity,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(activity,
                    "android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
                String[] strings = {android.Manifest.permission.ACCESS_FINE_LOCATION,
                        android.Manifest.permission.ACCESS_COARSE_LOCATION,
                        "android.permission.ACCESS_BACKGROUND_LOCATION"};
                ActivityCompat.requestPermissions(activity, strings, 2);
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            LocationManager alm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
            if (!alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
                Toast.makeText(activity, "请开启GPS！", Toast.LENGTH_SHORT).show();
            }
        }

        initBle(activity);

    }

    private static void initBle(Activity activity) {

        //初始化
        BleManager.getInstance().init(activity.getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(3, 5000)
                .setSplitWriteNum(20)
                .setConnectOverTime(10000)
                .setOperateTimeout(5000);
    }

    //扫描
    public static void search() {
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setScanTimeOut(10000)
                .setDeviceName(true, "BWTP010oN", "FHYDCSH2","QZ_MC")  // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                // 开始扫描（主线程）
                if (success) {
                    Log.d("体温", "开始");
                } else {
                    Log.d("体温", "失败");
                }

            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                // 扫描到一个符合扫描规则的BLE设备（主线程）
                Log.d("体温", "找到一个" + bleDevice.getName());
                scanning.number(bleDevice.getName(),bleDevice.getMac());
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                // 扫描结束，列出所有扫描到的符合扫描规则的BLE设备（主线程）
                Log.d("体温", "找到一个N个");
//                for (int i = 0; i < scanResultList.l; i++) {
//
//                }

            }
        });


    }

    public  void Macconnection(String deviceAddress) {
        BleManager.getInstance().setReConnectCount(3, 5000).connect(deviceAddress, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                Log.d("连接", "开始连接环境");
                ongoing=true;
//                        newe_1.setText("开始连接");
                receivedCallback.state(ongoing, Connectionstatus);//连接状态
            }
            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.d("连接", "失败环境");
//                        newe_1.setText("连接失败");

                Connectionstatus=false;
                receivedCallback.state(ongoing, Connectionstatus);//连接状态
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {

                Log.d("连接", "成功环境");
                Connectionstatus=true;
                receivedCallback.state(ongoing, Connectionstatus);//连接状态
                BleManager.getInstance().notify(
                        bleDevice,
                        SERVICE_UUID,
                        UUID_FFOA,
                        new BleNotifyCallback() {
                            @Override
                            public void onNotifySuccess() {
                                Log.d("通知云", "成功环境");
                                // 打开通知操作成功
                            }

                            @Override
                            public void onNotifyFailure(BleException exception) {
                                // 打开通知操作失败
                                Log.d("通知云", "失败环境");
//                                        temperature_data.setText("获取数据失败");
                            }

                            @Override
                            public void onCharacteristicChanged(byte[] data) {
                                Log.d("通知云", "环境" + data);

                                monReceivedata.data(data);
                                // 打开通知后，设备发过来的数据将在这里出现
                            }
                        });
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.d("连接", "断开环境");
                Connectionstatus=false;
                receivedCallback.state(ongoing, Connectionstatus);//连接状态
            }



        });

    }

    //蓝牙扫描
    public interface Onscanning {
        void number(String name, String Mac);
    }

    public void setscandata(Onscanning Onscanning) {
        this.scanning = Onscanning;
    }
    //蓝牙数据
    public interface OnReceivedata {
        void data(byte[] data);
    }
    public void setReceivedata(OnReceivedata onReceivedata) {
        this.monReceivedata = onReceivedata;
    }
    //连接状态回调
    public interface OnConnectionstatus {
        void state(boolean mIntheconnection, boolean mNotconnected);
    }
    public void setReceivedCallback(OnConnectionstatus onConnectionstatus) {
        this.receivedCallback = onConnectionstatus;
    }

}





